package storage

import (
	"bytes"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"

	"gitee.com/zh-jn/harmonica-previewer-online/api"
)

func NewLocalFileStorage(baseDir string) (api.Storage, error) {
	// ensure base dir
	if err := os.MkdirAll(baseDir, 0666); err != nil {
		return nil, err
	}

	return &LocalFileStorage{
		baseDir: baseDir,
	}, nil
}

type LocalFileStorage struct {
	baseDir string
}

func (s *LocalFileStorage) Get(key api.StorageKey) (io.Reader, error) {
	filename := filepath.Join(s.baseDir, string(key))
	buf, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return bytes.NewReader(buf), nil
}

func (s *LocalFileStorage) Put(key api.StorageKey, reader io.Reader) error {
	buf, err := ioutil.ReadAll(reader)
	if err != nil {
		return err
	}

	err = ioutil.WriteFile(filepath.Join(s.baseDir, string(key)), buf, 0666)
	if err != nil {
		return err
	}

	return nil
}

func (s *LocalFileStorage) Exists(key api.StorageKey) (bool, error) {
	path := filepath.Join(s.baseDir, string(key))
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}

	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
